package test.SpringMVC;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/file")
public class upfileController {
	
	@RequestMapping("/up")
	public void upload(HttpServletRequest request,HttpServletResponse response)
	{
		
		/*
		try {
			response.getWriter().println("ok");
			response.getWriter().close();
		} catch (IOException e) {
		
			e.printStackTrace();
		}
		return "";
		
		*/
		
		try {
			
			String savePath = request.getServletContext().getRealPath("/var/upload");
			File saveFileDir = new java.io.File(savePath);
			if (!saveFileDir.exists()) {
				saveFileDir.mkdirs();
			}
			// 创建工厂（这里用的是工厂模式）
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload up = new ServletFileUpload(factory);
			 List<FileItem> list = up.parseRequest(request);
			 FileItem file = list.get(0);
		        //获取文件名：
		        String fileName = file.getName();
		        //获取文件的类型：
		        String fileType = file.getContentType();
		        //获取文件的字节码：
		        InputStream in = file.getInputStream();
		        //文件大小
		        int size = file.getInputStream().available();
		        //声明输出字节流
		        OutputStream out = new FileOutputStream(savePath+"/"+fileName);
		        //文件copy
		        byte[] b = new byte[1024];
		        int len = 0;
		        while((len=in.read(b))!=-1){
		            out.write(b, 0, len);
		        }
		        out.flush(); 
		        out.close();
		        file.delete();
		        response.getOutputStream().println("upload ok!");
		        response.getOutputStream().close();
//			response.getWriter().close();
		} catch (IOException | FileUploadException e) {
			
			e.printStackTrace();
		}
		
//		return "";
		
	}
	

}
